﻿<template>
  <div class="page-container">
    <!-- 页面头部 -->
    <PageHeader title="合同管理">
      <!-- 搜索和筛选区域 -->
      <template #search-filters>
        <!-- 合同搜索 -->
        <div class="contract-search">
          <span class="label">合同搜索：</span>
          <el-tooltip content="支持搜索合同名称、供应商名称" placement="top">
            <el-icon class="help-icon"><QuestionFilled /></el-icon>
          </el-tooltip>
          <el-input
            v-model="searchParams.search"
            placeholder="搜索合同名称、供应商名称"
            style="width: 300px"
            clearable
            @input="handleSearch"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </div>

        <!-- 合同类型选择 -->
        <div class="contract-type-select">
          <span class="label">合同类型：</span>
          <el-tooltip content="选择合同类型进行筛选" placement="top">
            <el-icon class="help-icon"><QuestionFilled /></el-icon>
          </el-tooltip>
          <el-select
            v-model="searchParams.contractType"
            placeholder="合同类型"
            clearable
            style="width: 150px"
            @change="handleSearch"
          >
            <el-option label="项目合同" :value="1" />
            <el-option label="甲方合同" :value="2" />
            <el-option label="乙方合同" :value="3" />
            <el-option label="分摊合同" :value="4" />
          </el-select>
        </div>

        <!-- 合同状态选择 -->
        <div class="contract-status-select">
          <span class="label">合同状态：</span>
          <el-tooltip content="选择合同状态进行筛选" placement="top">
            <el-icon class="help-icon"><QuestionFilled /></el-icon>
          </el-tooltip>
          <el-select
            v-model="searchParams.contractStatus"
            placeholder="合同状态"
            clearable
            style="width: 150px"
            @change="handleSearch"
          >
            <el-option label="草稿" :value="0" />
            <el-option label="执行中" :value="1" />
            <el-option label="已完成" :value="2" />
            <el-option label="已终止" :value="3" />
          </el-select>
        </div>
      </template>

      <!-- 主要操作按钮 -->
      <template #main-actions>
        <el-button @click="handleAdd" type="primary">
          <el-icon><Plus /></el-icon>
          新建合同
        </el-button>
      </template>

      <!-- 更多操作下拉菜单 -->
      <template #more-actions>
        <el-dropdown @command="handleMoreAction">
          <el-button type="info">
            <el-icon><More /></el-icon>
            更多
          </el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="export">
                <el-tooltip content="导出当前筛选条件下的所有合同记录为Excel文件" placement="left">
                  <div style="display: flex; align-items: center; gap: 8px;">
                    <el-icon><Download /></el-icon>
                    导出Excel
                  </div>
                </el-tooltip>
              </el-dropdown-item>
              <el-dropdown-item command="columnConfig" icon="Setting">列配置</el-dropdown-item>
              <el-dropdown-item command="reset" icon="Refresh" divided>重置筛选</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </template>
    </PageHeader>

    <!-- 数据表格 -->
    <div class="table-container">
      <!-- 使用 BaseTable 组件 -->
      <BaseTable
        table-name="contract"
        :columns="tableColumns"
        :data="state.pageData"
        :loading="state.loading"
        :sort="sort"
        @sort-change="handleSortChange"
      >
        <!-- 合同类型插槽 -->
        <template #contractType="{ row }">
          <el-tag :type="getContractTypeTag(row.contractType)">
            {{ getContractTypeName(row.contractType) }}
          </el-tag>
        </template>
        
        <!-- 合同金额插槽 -->
        <template #contractAmount="{ row }">
          <span class="amount-text">¥{{ formatNumber(row.contractAmount) }}</span>
        </template>
        
        <!-- 变更金额插槽 -->
        <template #changeAmount="{ row }">
          <span class="amount-text">¥{{ formatNumber(row.changeAmount) }}</span>
        </template>
        
        <!-- 结算金额插槽 -->
        <template #settlementAmount="{ row }">
          <span class="amount-text">¥{{ formatNumber(row.settlementAmount) }}</span>
        </template>
        
        <!-- 已付款总额插槽 -->
        <template #totalPayment="{ row }">
          <span class="amount-text">¥{{ formatNumber(row.totalPayment) }}</span>
        </template>
        
        <!-- 合同状态插槽 -->
        <template #contractStatus="{ row }">
          <el-tag :type="getContractStatusTag(row.contractStatus)">
            {{ getContractStatusName(row.contractStatus) }}
          </el-tag>
        </template>
        
        <!-- 操作列插槽 -->
        <template #actions="{ row }">
          <div class="action-buttons">
            <el-button type="primary" size="small" @click="handleView(row)">
              <el-icon><View /></el-icon>
              查看
            </el-button>
            <el-button type="warning" size="small" @click="handleEdit(row)">
              <el-icon><Edit /></el-icon>
              编辑
            </el-button>
            <el-button type="info" size="small" @click="handleAttachments(row)">
              <el-icon><Document /></el-icon>
              附件
            </el-button>
            <el-button type="danger" size="small" @click="handleDelete(row)">
              <el-icon><Delete /></el-icon>
              删除
            </el-button>
          </div>
        </template>
      </BaseTable>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="state.currentPage"
          v-model:page-size="state.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="state.totalItems"
          layout="total, sizes, prev, pager, next, jumper"
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 新建/编辑合同对话框 -->
    <el-dialog 
      v-model="contractDialogVisible" 
      :title="dialogTitle" 
      width="800px"
      class="contract-dialog"
    >
      <el-form 
        :model="contractForm" 
        :rules="contractRules" 
        ref="contractFormRef" 
        label-width="120px"
        class="contract-form"
      >
        <!-- 基本信息 -->
        <div class="form-section">
          <div class="section-title">基本信息</div>
          <div class="form-row">
            <el-form-item label="合同编号" prop="contractNumber">
              <el-input
                v-model="contractForm.contractNumber"
                placeholder="请输入合同编号"
                @blur="checkContractNumber"
              />
            </el-form-item>
            <el-form-item label="合同名称" prop="contractName">
              <el-input
                v-model="contractForm.contractName"
                placeholder="请输入合同名称"
              />
            </el-form-item>
          </div>
          
          <div class="form-row">
            <el-form-item label="合同类型" prop="contractType">
              <el-select
                v-model="contractForm.contractType"
                placeholder="选择合同类型"
                style="width: 100%"
              >
              <el-option label="项目合同" :value="1" />
            <el-option label="甲方合同" :value="2" />
            <el-option label="乙方合同" :value="3" />
            <el-option label="分摊合同" :value="4" />
              </el-select>
            </el-form-item>
            <el-form-item label="合同状态" prop="contractStatus">
              <el-select
                v-model="contractForm.contractStatus"
                placeholder="选择合同状态"
                style="width: 100%"
              >
                <el-option label="草稿" :value="0" />
                <el-option label="执行中" :value="1" />
                <el-option label="已完成" :value="2" />
                <el-option label="已终止" :value="3" />
              </el-select>
            </el-form-item>
          </div>
          
          <div class="form-row">
            <el-form-item label="供应商名称" prop="supplierName">
              <el-input
                v-model="contractForm.supplierName"
                placeholder="请输入供应商名称"
              />
            </el-form-item>
            <el-form-item label="签约日期" prop="signDate">
              <el-date-picker
                v-model="contractForm.signDate"
                type="date"
                placeholder="选择签约日期"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                style="width: 100%"
              />
            </el-form-item>
          </div>
          
          <div class="form-row">
            <el-form-item label="合同金额" prop="contractAmount">
              <el-input-number
                v-model="contractForm.contractAmount"
                :precision="2"
                :min="0"
                placeholder="请输入合同金额"
                style="width: 100%"
              />
            </el-form-item>
            <el-form-item label="变更金额" prop="changeAmount">
              <el-input-number
                v-model="contractForm.changeAmount"
                :precision="2"
                :min="0"
                placeholder="请输入变更金额"
                style="width: 100%"
              />
            </el-form-item>
          </div>
          
          <div class="form-row">
            <el-form-item label="结算金额" prop="settlementAmount">
              <el-input-number
                v-model="contractForm.settlementAmount"
                :precision="2"
                :min="0"
                placeholder="请输入结算金额"
                style="width: 100%"
              />
            </el-form-item>
            <el-form-item label="结算日期" prop="settlementDate">
              <el-date-picker
                v-model="contractForm.settlementDate"
                type="date"
                placeholder="选择结算日期"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                style="width: 100%"
              />
            </el-form-item>
          </div>
        </div>

        <!-- 备注信息 -->
        <div class="form-section">
          <div class="section-title">备注信息</div>
          <div class="form-row single">
            <el-form-item label="备注" prop="remark">
              <el-input
                v-model="contractForm.remark"
                type="textarea"
                :rows="3"
                placeholder="请输入备注"
              />
            </el-form-item>
          </div>
        </div>

        <!-- 附件上传 -->
        <div class="form-section">
          <div class="section-title">附件上传</div>
          <div class="form-row single">
            <el-form-item label="附件">
              <el-upload
                ref="uploadRef"
                :action="uploadUrl"
                :headers="uploadHeaders"
                :data="uploadData"
                :file-list="fileList"
                :on-preview="handleFilePreview"
                :on-remove="handleFileRemove"
                :on-success="handleFileSuccess"
                :on-error="handleFileError"
                :before-upload="beforeFileUpload"
                multiple
                :limit="10"
                :file-size="10"
                accept=".jpg,.jpeg,.png,.gif,.pdf,.doc,.docx,.xls,.xlsx"
                list-type="text"
                class="upload-area"
              >
                <el-icon><Plus /></el-icon>
                <div class="upload-text">点击上传</div>
              </el-upload>
            </el-form-item>
          </div>
        </div>
      </el-form>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="contractDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitContract" :loading="submitLoading">
            保存
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 合同详情对话框 -->
    <el-dialog 
      v-model="detailDialogVisible" 
      title="合同详情" 
      width="1000px"
      class="contract-detail-dialog"
    >
      <div v-if="selectedContract" class="contract-detail">
        <div class="detail-section">
          <h3>基本信息</h3>
          <el-descriptions :column="2" border>
            <el-descriptions-item label="合同编号">{{ selectedContract.contractNumber }}</el-descriptions-item>
            <el-descriptions-item label="合同名称">{{ selectedContract.contractName }}</el-descriptions-item>
            <el-descriptions-item label="合同类型">{{ getContractTypeName(selectedContract.contractType) }}</el-descriptions-item>
            <el-descriptions-item label="合同状态">{{ getContractStatusName(selectedContract.contractStatus) }}</el-descriptions-item>
            <el-descriptions-item label="供应商名称">{{ selectedContract.supplierName }}</el-descriptions-item>
            <el-descriptions-item label="签约日期">{{ selectedContract.signDate }}</el-descriptions-item>
            <el-descriptions-item label="合同金额">¥{{ formatNumber(selectedContract.contractAmount) }}</el-descriptions-item>
            <el-descriptions-item label="变更金额">¥{{ formatNumber(selectedContract.changeAmount) }}</el-descriptions-item>
            <el-descriptions-item label="结算金额">¥{{ formatNumber(selectedContract.settlementAmount) }}</el-descriptions-item>
            <el-descriptions-item label="结算日期">{{ selectedContract.settlementDate || '-' }}</el-descriptions-item>
            <el-descriptions-item label="已付款总额">¥{{ formatNumber(selectedContract.totalPayment) }}</el-descriptions-item>
            <el-descriptions-item label="备注">{{ selectedContract.remark || '-' }}</el-descriptions-item>
          </el-descriptions>
        </div>
        
        <div class="detail-section">
          <h3>付款记录</h3>
          <el-table :data="paymentRecords" border style="width: 100%">
            <el-table-column prop="paymentNumber" label="付款编号" width="120" />
            <el-table-column prop="paymentDate" label="付款日期" width="120" />
            <el-table-column prop="paymentSummary" label="付款摘要" />
            <el-table-column prop="paymentAmount" label="付款金额" width="120" align="right">
              <template #default="scope">
                ¥{{ formatNumber(scope.row.paymentAmount) }}
              </template>
            </el-table-column>
            <el-table-column prop="supplierAccountName" label="供应商账户" width="150" />
            <el-table-column prop="voucherNumber" label="凭证号" width="120" />
          </el-table>
        </div>
      </div>
    </el-dialog>

        <!-- 附件对话框 -->
    <el-dialog 
      v-model="attachmentDialogVisible" 
      title="合同附件" 
      width="800px"
      class="attachment-dialog"
    >
      <div v-if="selectedContract" class="attachment-content">
        <div class="contract-info">
          <h4>{{ selectedContract.contractName }}</h4>
          <p>合同编号：{{ selectedContract.contractNumber }}</p>
        </div>
        
        <div class="attachment-list" v-if="attachmentList.length > 0">
          <div class="attachment-item" v-for="attachment in attachmentList" :key="attachment.id">
            <div class="attachment-info">
              <div class="attachment-name">{{ attachment.originalFilename }}</div>
              <div class="attachment-meta">
                <span class="file-size">{{ formatFileSize(attachment.fileSize) }}</span>
                <span class="file-type">{{ attachment.fileType }}</span>
                <span class="upload-time">{{ formatDate(attachment.createTime) }}</span>
                <span v-if="attachment.subDirectory" class="sub-directory">目录: {{ attachment.subDirectory }}</span>
              </div>
            </div>
            <div class="attachment-actions">
              <el-button type="primary" size="small" @click="previewAttachment(attachment)">
                <el-icon><View /></el-icon>
                预览
              </el-button>
              <el-button type="success" size="small" @click="downloadAttachment(attachment)">
                <el-icon><Download /></el-icon>
                下载
              </el-button>
            </div>
          </div>
        </div>
        
        <div v-else class="no-attachments">
          <el-empty description="暂无附件" />
        </div>
      </div>
    </el-dialog>

    <!-- 列配置对话框 -->
    <el-dialog v-model="columnConfigVisible" title="列配置" width="600px" class="column-config-dialog">
      <div class="column-config">
        <div class="column-list">
          <div v-for="column in tableColumns" :key="column.prop" class="column-item">
            <div class="column-info">
              <el-checkbox 
                v-model="column.visible" 
                :label="column.label"
                @change="handleColumnVisibilityChange"
              />
            </div>
            <div class="column-width" v-if="column.visible">
              <span class="width-label">宽度:</span>
              <el-input-number
                v-model="column.width"
                :min="80"
                :max="500"
                :step="10"
                size="small"
                style="width: 100px;"
                @change="handleColumnWidthChange"
              />
              <span class="unit">px</span>
            </div>
          </div>
        </div>
      </div>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="resetColumnConfig">重置</el-button>
          <el-button type="primary" @click="saveColumnConfig">保存</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed, nextTick } from 'vue'
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus'
import { 
  Plus, Search, ArrowDown, Edit, Delete, View, 
  Document, Download, Refresh, Setting, QuestionFilled, More
} from '@element-plus/icons-vue'
import BaseTable from '@/components/tools/BaseTable.vue'
import PageHeader from '@/components/layout/PageHeader.vue'
import useTable from '@/composables/useTable.js'
import contractApi from '@/api/contractApi'
import attachmentApi from '@/api/attachmentApi'

// 使用通用表格组件
const { state, loadData, handleSortChange, updateSearchParams, handleSizeChange, handleCurrentChange } = useTable(contractApi.getList)

// 搜索参数
const searchParams = reactive({
  search: '',
  contractType: null,
  contractStatus: null
})

// 排序参数
const sort = ref({})

// 表格列配置 - 包含所有字段，默认显示主要字段
const tableColumns = ref([
  // 主要字段 - 默认显示
  { prop: 'contractNumber', label: '合同编号', minWidth: 120, visible: true },
  { prop: 'contractName', label: '合同名称', minWidth: 250, visible: true },
  { prop: 'contractType', label: '合同类型', minWidth: 140, visible: true, slot: 'contractType' },
  { prop: 'supplierName', label: '供应商名称', minWidth: 180, visible: true },
  { prop: 'signDate', label: '签约日期', minWidth: 120, visible: true },
  { prop: 'contractAmount', label: '合同金额', minWidth: 140, align: 'right', visible: true, slot: 'contractAmount' },
  { prop: 'changeAmount', label: '变更金额', minWidth: 140, align: 'right', visible: true, slot: 'changeAmount' },
  { prop: 'settlementAmount', label: '结算金额', minWidth: 140, align: 'right', visible: true, slot: 'settlementAmount' },
  { prop: 'totalPayment', label: '已付款总额', minWidth: 140, align: 'right', visible: true, slot: 'totalPayment' },
  { prop: 'contractStatus', label: '合同状态', minWidth: 100, visible: true, slot: 'contractStatus' },
  { prop: 'settlementDate', label: '结算日期', minWidth: 120, visible: true },
  // 次要字段 - 默认隐藏
  { prop: 'subjectId', label: '科目ID', minWidth: 100, visible: false },
  { prop: 'subjectName', label: '科目名称', minWidth: 150, visible: false },
  { prop: 'attachmentIds', label: '附件ID', minWidth: 100, visible: false },
  { prop: 'remark', label: '备注', minWidth: 180, visible: false },
  { prop: 'createBy', label: '创建人ID', minWidth: 100, visible: false },
  { prop: 'createByName', label: '创建人', minWidth: 100, visible: false },
  { prop: 'createTime', label: '创建时间', minWidth: 140, visible: false },
  { prop: 'updateBy', label: '修改人ID', minWidth: 100, visible: false },
  { prop: 'updateByName', label: '修改人', minWidth: 100, visible: false },
  { prop: 'updateTime', label: '更新时间', minWidth: 140, visible: false },
  { prop: 'status', label: '状态', minWidth: 80, visible: false },
  { prop: 'id', label: 'ID', minWidth: 80, visible: false },
  { prop: 'actions', label: '操作', minWidth: 300, visible: true, slot: 'actions', fixed: 'right' }
])

// 对话框相关
const contractDialogVisible = ref(false)
const detailDialogVisible = ref(false)
const dialogTitle = ref('')
const submitLoading = ref(false)
const contractFormRef = ref()

// 列配置相关
const columnConfigVisible = ref(false)
const originalTableColumns = ref([])

// 表单数据
const contractForm = reactive({
  id: null,
  contractNumber: '',
  contractName: '',
  contractType: null,
  supplierName: '',
  signDate: '',
  contractAmount: null,
  changeAmount: null,
  settlementAmount: null,
  settlementDate: '',
  subjectId: null,
  contractStatus: null,
  remark: '',
  attachmentIds: ''
})

// 表单验证规则
const contractRules = {
  contractName: [{ required: true, message: '请输入合同名称', trigger: 'blur' }],
  supplierName: [{ required: true, message: '请输入供应商名称', trigger: 'blur' }],
  signDate: [{ required: true, message: '请选择签约日期', trigger: 'change' }],
  contractAmount: [{ required: true, message: '请输入合同金额', trigger: 'blur' }],
  contractType: [{ required: true, message: '请选择合同类型', trigger: 'change' }],
  contractStatus: [{ required: true, message: '请选择合同状态', trigger: 'change' }]
}

// 文件上传相关
const uploadRef = ref()
const fileList = ref([])
const uploadUrl = '/api/attachments/upload'
const uploadHeaders = {
  'Authorization': `Bearer ${localStorage.getItem('token')}`
}

// 上传时添加子目录参数
const uploadData = {
  subDirectory: 'contract'
}

// 详情相关
const selectedContract = ref(null)
const paymentRecords = ref([])

// 附件相关
const attachmentDialogVisible = ref(false)
const attachmentList = ref([])

// 方法
const handleSearch = () => {
  updateSearchParams(searchParams)
  loadData()
}

const handleAdd = () => {
  dialogTitle.value = '新建合同'
  resetContractForm()
  contractDialogVisible.value = true
}

const handleEdit = (row) => {
  dialogTitle.value = '编辑合同'
  Object.assign(contractForm, row)
  if (row.attachmentIds) {
    loadAttachments(row.attachmentIds)
  } else {
    fileList.value = []
  }
  contractDialogVisible.value = true
}

const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除这个合同吗？', '确认删除', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await contractApi.delete(row.id)
    ElMessage.success('删除成功')
    loadData()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

const handleView = async (row) => {
  selectedContract.value = row
  try {
    const response = await contractApi.getPayments(row.id)
    paymentRecords.value = response.data || response || []
  } catch (error) {
    console.error('获取付款记录失败:', error)
    paymentRecords.value = []
  }
  detailDialogVisible.value = true
}

const handleAttachments = async (row) => {
  selectedContract.value = row
  attachmentDialogVisible.value = true
  
  if (row.attachmentIds) {
    try {
      const ids = row.attachmentIds.split(',').map(id => parseInt(id.trim())).filter(id => !isNaN(id))
      if (ids.length > 0) {
        const response = await attachmentApi.getAttachmentsBatch(ids)
        attachmentList.value = response.data || response || []
      } else {
        attachmentList.value = []
      }
    } catch (error) {
      console.error('获取附件失败:', error)
      ElMessage.error('获取附件失败')
      attachmentList.value = []
    }
  } else {
    attachmentList.value = []
  }
}

const handleMoreAction = (command) => {
  switch (command) {
    case 'export':
      handleExport()
      break
    case 'columnConfig':
      showColumnConfig()
      break
    case 'reset':
      Object.assign(searchParams, {
        search: '',
        contractType: null,
        contractStatus: null
      })
      handleSearch()
      break
  }
}



// 列配置相关函数
const showColumnConfig = () => {
  columnConfigVisible.value = true
}

// 处理列显示/隐藏变化
const handleColumnVisibilityChange = () => {
  console.log('列可见性变化 - tableColumns:', tableColumns.value)
  // 强制更新表格
  nextTick(() => {
    // 触发表格重新渲染
  })
}

// 处理列宽变化
const handleColumnWidthChange = () => {
  // 强制更新表格
  nextTick(() => {
    // 触发表格重新渲染
  })
}

// 重置列配置
const resetColumnConfig = () => {
  // 恢复原始列配置
  tableColumns.value.forEach((column, index) => {
    if (originalTableColumns.value[index]) {
      column.visible = originalTableColumns.value[index].visible
      column.width = originalTableColumns.value[index].width
    }
  })
  ElMessage.success('列配置已重置')
}

// 保存列配置
const saveColumnConfig = () => {
  // 保存到localStorage
  localStorage.setItem('contractTableColumns', JSON.stringify(tableColumns.value))
  columnConfigVisible.value = false
  ElMessage.success('列配置已保存')
}

const resetContractForm = () => {
  Object.assign(contractForm, {
    id: null,
    contractNumber: '',
    contractName: '',
    contractType: null,
    supplierName: '',
    signDate: '',
    contractAmount: null,
    changeAmount: null,
    settlementAmount: null,
    settlementDate: '',
    subjectId: null,
    contractStatus: null,
    remark: '',
    attachmentIds: ''
  })
  fileList.value = []
}

const submitContract = async () => {
  try {
    await contractFormRef.value.validate()
    submitLoading.value = true
    
    // 处理附件ID
    const attachmentIds = fileList.value
      .filter(file => file.response && file.response.id)
      .map(file => file.response.id)
      .join(',')
    
    const submitData = {
      ...contractForm,
      attachmentIds
    }
    
    if (contractForm.id) {
      // 编辑模式
      await contractApi.update(contractForm.id, submitData)
      ElMessage.success('编辑成功')
    } else {
      // 新建模式
      await contractApi.create(submitData)
      ElMessage.success('新建成功')
    }
    
    contractDialogVisible.value = false
    loadData()
  } catch (error) {
    console.error('提交失败:', error)
    ElMessage.error('提交失败')
  } finally {
    submitLoading.value = false
  }
}

const checkContractNumber = async () => {
  if (!contractForm.contractNumber) return
  
  try {
    const response = await contractApi.checkContractNumber(contractForm.contractNumber)
    if (response.data === false) {
      ElMessage.warning('合同编号已存在')
    }
  } catch (error) {
    console.error('检查合同编号失败:', error)
  }
}

// 文件上传相关方法
const beforeFileUpload = (file) => {
  const isValidType = /\.(jpg|jpeg|png|gif|pdf|doc|docx|xls|xlsx)$/.test(file.name.toLowerCase())
  const isLt10M = file.size / 1024 / 1024 < 10
  
  if (!isValidType) {
    ElMessage.error('只能上传图片、PDF、Word、Excel文件!')
    return false
  }
  if (!isLt10M) {
    ElMessage.error('文件大小不能超过10MB!')
    return false
  }
  return true
}

const handleFileSuccess = (response, file) => {
  file.response = response.data || response
  ElMessage.success('上传成功')
  console.log('文件上传成功:', response)
}

const handleFileError = (error, file) => {
  console.error('文件上传失败:', error)
  ElMessage.error('上传失败')
}

const handleFilePreview = (file) => {
  if (file.url) {
    window.open(file.url)
  }
}

const handleFileRemove = (file) => {
  console.log('移除文件:', file)
}

const loadAttachments = async (attachmentIds) => {
  if (!attachmentIds) return
  
  try {
    const ids = attachmentIds.split(',').map(id => parseInt(id.trim())).filter(id => !isNaN(id))
    if (ids.length === 0) {
      fileList.value = []
      return
    }
    
    const response = await attachmentApi.getAttachmentsBatch(ids)
    const attachments = response.data || response || []
    
    fileList.value = attachments.map(attachment => ({
      name: attachment.originalFilename || `附件_${attachment.id}`,
      uid: attachment.id,
      status: 'success',
      response: attachment
    }))
    
    console.log('加载的附件列表:', fileList.value)
  } catch (error) {
    console.error('加载附件失败:', error)
    ElMessage.error('加载附件失败')
    fileList.value = []
  }
}

const handleExport = async () => {
  try {
    // 显示确认对话框
    await ElMessageBox.confirm(
      '确定要导出合同列表吗？导出的Excel文件将包含所有符合条件的合同记录。',
      '确认导出',
      {
        confirmButtonText: '确定导出',
        cancelButtonText: '取消',
        type: 'info'
      }
    )
    
    // 显示导出提示
    const loadingMessage = ElMessage({
      message: '正在导出Excel文件，请稍候...',
      type: 'info',
      duration: 0,
      showClose: false
    })
    
    // 构建导出参数，支持搜索和筛选条件
    const exportParams = {}
    
    // 添加搜索参数
    if (searchParams.search) {
      exportParams.search = searchParams.search
    }
    
    // 添加合同类型筛选
    if (searchParams.contractType !== null && searchParams.contractType !== undefined) {
      exportParams.contractType = searchParams.contractType
    }
    
    // 添加合同状态筛选
    if (searchParams.contractStatus !== null && searchParams.contractStatus !== undefined) {
      exportParams.contractStatus = searchParams.contractStatus
    }
    
    console.log('导出参数:', exportParams)
    
    const response = await contractApi.exportData(exportParams)
    
    // 关闭加载提示
    loadingMessage.close()
    
    // 创建Blob对象
    const blob = new Blob([response.data], {
      type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
    })
    
    // 生成下载链接
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    
    // 生成文件名，包含当前日期和筛选条件
    const today = new Date()
    const dateStr = today.toISOString().split('T')[0]
    let fileName = `合同列表_${dateStr}`
    
    // 如果有筛选条件，添加到文件名中
    if (searchParams.search) {
      fileName += `_搜索_${searchParams.search}`
    }
    if (searchParams.contractType !== null && searchParams.contractType !== undefined) {
      const typeName = getContractTypeName(searchParams.contractType)
      fileName += `_${typeName}`
    }
    if (searchParams.contractStatus !== null && searchParams.contractStatus !== undefined) {
      const statusName = getContractStatusName(searchParams.contractStatus)
      fileName += `_${statusName}`
    }
    
    link.download = `${fileName}.xlsx`
    
    // 触发下载
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    
    // 清理URL对象
    setTimeout(() => window.URL.revokeObjectURL(url), 1000)
    
    ElMessage.success('导出成功')
  } catch (error) {
    console.error('导出失败:', error)
    
    // 根据错误类型显示不同的错误信息
    if (error.response?.status === 401) {
      ElMessage.error('未授权，请重新登录')
    } else if (error.response?.status === 403) {
      ElMessage.error('权限不足，无法导出')
    } else if (error.response?.status === 400) {
      ElMessage.error('请求参数错误')
    } else if (error.response?.status === 404) {
      ElMessage.error('导出接口不存在')
    } else if (error.response?.status === 500) {
      ElMessage.error('服务器内部错误，请稍后重试')
    } else if (error.code === 'ERR_NETWORK') {
      ElMessage.error('网络连接失败，请检查网络')
    } else {
      ElMessage.error('导出失败，请稍后重试')
    }
  }
}

// 工具方法
const formatNumber = (value) => {
  if (value === null || value === undefined) return '0.00'
  return new Intl.NumberFormat('zh-CN', {
    minimumFractionDigits: 2,
    maximumFractionDigits: 2
  }).format(value)
}

const getContractTypeName = (type) => {
  const types = {
    1: '项目合同',
    2: '甲方合同',
    3: '乙方合同',
    4: '分摊合同'
  }
  return types[type] || '未知'
}

const getContractStatusName = (status) => {
  const statuses = {
    0: '草稿',
    1: '执行中',
    2: '已完成',
    3: '已终止'
  }
  return statuses[status] || '未知'
}

const getContractTypeTag = (type) => {
  const tags = {
    1: 'primary',
    2: 'success',
    3: 'warning',
    4: 'info'
  }
  return tags[type] || 'default'
}

const getContractStatusTag = (status) => {
  const tags = {
    0: 'info',
    1: 'primary',
    2: 'success',
    3: 'danger'
  }
  return tags[status] || 'default'
}

// 附件相关方法
const previewAttachment = async (attachment) => {
  // 显示加载提示
  const loadingInstance = ElLoading.service({
    lock: true,
    text: '正在加载预览...',
    background: 'rgba(0, 0, 0, 0.7)'
  })
  
  try {
    const response = await attachmentApi.previewAttachment(attachment.id)
    const blob = new Blob([response.data], { type: attachment.fileType || 'application/octet-stream' })
    const url = window.URL.createObjectURL(blob)
    window.open(url, '_blank')
    // 清理URL对象
    setTimeout(() => window.URL.revokeObjectURL(url), 1000)
    ElMessage.success('预览已打开')
  } catch (error) {
    console.error('预览附件失败:', error)
    ElMessage.error('预览失败')
  } finally {
    loadingInstance.close()
  }
}

const downloadAttachment = async (attachment) => {
  // 显示加载提示
  const loadingInstance = ElLoading.service({
    lock: true,
    text: '正在准备下载...',
    background: 'rgba(0, 0, 0, 0.7)'
  })
  
  try {
    const response = await attachmentApi.downloadAttachment(attachment.id)
    const blob = new Blob([response.data], { type: attachment.fileType || 'application/octet-stream' })
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = attachment.originalFilename || `附件_${attachment.id}`
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    // 清理URL对象
    setTimeout(() => window.URL.revokeObjectURL(url), 1000)
    ElMessage.success('下载成功')
  } catch (error) {
    console.error('下载附件失败:', error)
    ElMessage.error('下载失败')
  } finally {
    loadingInstance.close()
  }
}

const formatFileSize = (bytes) => {
  if (!bytes) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN') + ' ' + date.toLocaleTimeString('zh-CN', { hour12: false })
}

// 初始化
onMounted(() => {
  // 保存原始列配置用于重置
  originalTableColumns.value = JSON.parse(JSON.stringify(tableColumns.value))
  
  // 加载保存的列配置
  const savedConfig = localStorage.getItem('contractTableColumns')
  if (savedConfig) {
    try {
      const savedColumns = JSON.parse(savedConfig)
      tableColumns.value.forEach((column, index) => {
        const savedColumn = savedColumns.find(c => c.prop === column.prop)
        if (savedColumn) {
          column.visible = savedColumn.visible
          column.width = savedColumn.width
        }
      })
    } catch (error) {
      console.error('加载列配置失败:', error)
    }
  }
  
  loadData()
})
</script>

<style scoped>
.page-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: #f5f7fa;
  overflow: hidden;
}

/* 搜索区域样式 */
.contract-search,
.contract-type-select,
.contract-status-select {
  display: flex;
  align-items: center;
  gap: 8px;
}

.label {
  color: var(--primary-color, #409eff);
  font-weight: 500;
  white-space: nowrap;
}

.help-icon {
  color: #909399;
  font-size: 14px;
  margin-left: 4px;
  cursor: pointer;
  transition: color 0.3s ease;
}

.help-icon:hover {
  color: var(--primary-color, #409eff);
}

.table-container {
  flex: 1;
  width: 100%;
  min-height: 0;
  max-width: 100%;
  background: white;
  border-radius: 10px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
  border: 1px solid rgba(0, 0, 0, 0.05);
  padding: 20px;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  box-sizing: border-box;
}

.table-container .base-table-container {
  flex: 1;
  width: 100%;
  min-height: 0;
  max-width: 100%;
  display: flex;
  flex-direction: column;
  box-sizing: border-box;
}

.table-container :deep(.el-table) {
  width: 100% !important;
  border-radius: 8px;
  overflow: hidden;
}

.table-container .base-table-container {
  flex: 1;
  width: 100%;
  min-height: 0;
  display: flex;
  flex-direction: column;
}

/* 表格样式与主题协调 */
.table-container :deep(.el-table) {
  border-radius: 8px;
  overflow: hidden;
}

.table-container :deep(.el-table__header) {
  background: var(--primary-color, #409eff);
}

.table-container :deep(.el-table__header th) {
  background: var(--primary-color, #409eff) !important;
  color: white !important;
  font-weight: 600;
  padding: 5px !important;
}

.table-container :deep(.el-table__body tr:hover) {
  background-color: rgba(64, 158, 255, 0.1);
}

/* 表格行padding设置 */
.table-container :deep(.el-table__body td) {
  padding: 5px !important;
}

/* 对话框样式 */
.contract-dialog {
  border-radius: 12px;
  overflow: hidden;
}

.contract-dialog :deep(.el-dialog__header) {
  background: var(--primary-color, #409eff);
  color: white;
  padding: 20px;
  margin: 0;
}

.contract-dialog :deep(.el-dialog__body) {
  padding: 20px;
}

.contract-dialog :deep(.el-dialog__footer) {
  padding: 15px 20px;
  border-top: 1px solid #e4e7ed;
}

.contract-form {
  max-height: 60vh;
  overflow-y: auto;
}

.form-section {
  margin-bottom: 20px;
  padding: 15px;
  background: rgba(248, 250, 252, 0.5);
  border-radius: 8px;
  border: 1px solid rgba(0, 0, 0, 0.05);
}

.section-title {
  font-size: 16px;
  font-weight: 600;
  color: var(--primary-color, #409eff);
  margin-bottom: 15px;
  padding-bottom: 8px;
  border-bottom: 2px solid var(--primary-color, #409eff);
}

.form-row {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20px;
  margin-bottom: 15px;
}

.form-row.single {
  grid-template-columns: 1fr;
}

.upload-area {
  border: 2px dashed #d9d9d9;
  border-radius: 6px;
  padding: 20px;
  text-align: center;
  transition: border-color 0.3s;
}

.upload-area:hover {
  border-color: var(--primary-color, #409eff);
}

.upload-text {
  margin-top: 10px;
  color: #666;
}

/* 详情对话框样式 */
.contract-detail-dialog {
  border-radius: 12px;
  overflow: hidden;
}

.contract-detail-dialog :deep(.el-dialog__header) {
  background: var(--primary-color, #409eff);
  color: white;
  padding: 20px;
  margin: 0;
}

.contract-detail-dialog :deep(.el-dialog__body) {
  padding: 20px;
}

.detail-section {
  margin-bottom: 30px;
}

  .detail-section h3 {
    color: var(--primary-color, #409eff);
    margin-bottom: 15px;
    font-size: 18px;
    font-weight: 600;
  }
  
  /* 附件对话框样式 */
  .attachment-dialog {
    border-radius: 12px;
    overflow: hidden;
  }
  
  .attachment-dialog :deep(.el-dialog__header) {
    background: var(--primary-color, #409eff);
    color: white;
    padding: 20px;
    margin: 0;
  }
  
  .attachment-dialog :deep(.el-dialog__body) {
    padding: 20px;
  }
  
  .attachment-content {
    max-height: 500px;
    overflow-y: auto;
  }
  
  .contract-info {
    margin-bottom: 20px;
    padding-bottom: 15px;
    border-bottom: 1px solid #e4e7ed;
  }
  
  .contract-info h4 {
    color: var(--primary-color, #409eff);
    margin: 0 0 10px 0;
    font-size: 18px;
    font-weight: 600;
  }
  
  .contract-info p {
    color: #666;
    margin: 0;
    font-size: 14px;
  }
  
  .attachment-list {
    display: flex;
    flex-direction: column;
    gap: 15px;
  }
  
  .attachment-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 15px;
    border: 1px solid #e4e7ed;
    border-radius: 8px;
    background: #fafafa;
    transition: all 0.3s;
  }
  
  .attachment-item:hover {
    border-color: var(--primary-color, #409eff);
    background: #f0f8ff;
  }
  
  .attachment-info {
    flex: 1;
  }
  
  .attachment-name {
    font-weight: 600;
    color: #303133;
    margin-bottom: 5px;
    font-size: 14px;
  }
  
  .attachment-meta {
    display: flex;
    gap: 15px;
    font-size: 12px;
    color: #909399;
  }
  
  .attachment-actions {
    display: flex;
    gap: 8px;
  }
  
  .no-attachments {
    text-align: center;
    padding: 40px 20px;
  }
  
  /* 操作按钮样式 */
  .action-buttons {
    display: flex;
    gap: 5px;
    flex-wrap: wrap;
  }
  
  .action-buttons .el-button {
    margin: 0;
  }
  
  /* 金额文本样式 */
  .amount-text {
    font-weight: normal;
    color: #303133;
  }
  
  /* 表格容器滚动条样式 */
  .table-container::-webkit-scrollbar {
    width: 8px;
    height: 8px;
  }
  
  .table-container::-webkit-scrollbar-track {
    background: #f1f1f1;
    border-radius: 4px;
  }
  
  .table-container::-webkit-scrollbar-thumb {
    background: #c1c1c1;
    border-radius: 4px;
  }
  
  .table-container::-webkit-scrollbar-thumb:hover {
    background: #a8a8a8;
  }
  
  /* 分页器样式 */
  .pagination-wrapper {
    padding: 20px;
    background: white;
    display: flex;
    justify-content: center;
    align-items: center;
    border-top: 1px solid #e4e7ed;
    box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.05);
    margin-top: 10px;
    border-radius: 0 0 8px 8px;
  }

  .pagination-wrapper .el-pagination {
    --el-pagination-bg-color: transparent;
    --el-pagination-text-color: #606266;
    --el-pagination-border-radius: 4px;
    --el-pagination-button-color: #606266;
    --el-pagination-button-bg-color: #ffffff;
    --el-pagination-button-disabled-color: #c0c4cc;
    --el-pagination-button-disabled-bg-color: #ffffff;
    --el-pagination-hover-color: #409eff;
    --el-pagination-hover-bg-color: #ecf5ff;
  }

  .pagination-wrapper .el-pagination .el-pager li {
    border-radius: 4px;
    margin: 0 2px;
    transition: all 0.3s ease;
  }

  .pagination-wrapper .el-pagination .el-pager li.is-active {
    background-color: #409eff;
    color: white;
    font-weight: 600;
  }

  .pagination-wrapper .el-pagination .el-pager li:hover {
    background-color: #ecf5ff;
    color: #409eff;
  }

  .pagination-wrapper .el-pagination .btn-prev,
  .pagination-wrapper .el-pagination .btn-next {
    border-radius: 4px;
    margin: 0 4px;
    transition: all 0.3s ease;
  }

  .pagination-wrapper .el-pagination .btn-prev:hover,
  .pagination-wrapper .el-pagination .btn-next:hover {
    background-color: #ecf5ff;
    color: #409eff;
  }

  .pagination-wrapper .el-pagination .el-pagination__sizes {
    margin-right: 15px;
  }

  .pagination-wrapper .el-pagination .el-pagination__jump {
    margin-left: 15px;
  }

  /* 分页器响应式设计 */
  @media (max-width: 768px) {
    .pagination-wrapper {
      padding: 15px 10px;
    }
    
    .pagination-wrapper .el-pagination {
      font-size: 12px;
    }
    
    .pagination-wrapper .el-pagination .el-pagination__sizes {
      margin-right: 10px;
    }
    
    .pagination-wrapper .el-pagination .el-pagination__jump {
      margin-left: 10px;
    }
  }

  @media (max-width: 480px) {
    .pagination-wrapper {
      flex-direction: column;
      gap: 10px;
    }
    
    .pagination-wrapper .el-pagination {
      justify-content: center;
    }
  }

/* 响应式设计 */
@media (max-width: 1920px) {
  .page-container {
    padding: 15px;
  }
  
  .header-row {
    gap: 15px;
  }
  
  .search-area {
    gap: 10px;
  }
  
  .search-area .el-input {
    width: 250px !important;
  }
  
  .search-area .el-select {
    width: 120px !important;
  }
}

@media (max-width: 1600px) {
  .page-container {
    padding: 10px;
  }
  
  .header-row {
    gap: 10px;
  }
  
  .search-area {
    flex-direction: column;
    align-items: stretch;
    gap: 8px;
  }
  
  .action-area {
    flex-direction: column;
    align-items: stretch;
    gap: 8px;
  }
  
  .search-area .el-input {
    width: 100% !important;
  }
  
  .search-area .el-select {
    width: 100% !important;
  }
}

@media (max-width: 1200px) {
  .header-row {
    flex-direction: column;
    align-items: stretch;
    gap: 15px;
  }
  
  .form-row {
    grid-template-columns: 1fr;
  }
}

@media (max-width: 768px) {
  .page-header {
    padding: 15px;
  }
  
  .table-container {
    padding: 8px;
  }
  
  .action-buttons {
    flex-direction: column;
    gap: 3px;
  }
  
  .action-buttons .el-button {
    width: 100%;
  }
  
  .pagination-wrapper {
    padding: 10px;
  }
}

/* 列配置样式 */
.column-config {
  max-height: 500px;
  overflow-y: auto;
}

.column-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.column-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px;
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  background: #fafafa;
}

.column-info {
  flex: 1;
}

.column-width {
  display: flex;
  align-items: center;
  gap: 8px;
}

.width-label {
  font-size: 12px;
  color: #606266;
}

.unit {
  font-size: 12px;
  color: #909399;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>
